import React, { useState, useCallback, useEffect, useRef } from 'react';
import { useHistory } from 'react-router';
import { getUserList } from '../api/user';
import { FormattedMessage, request } from 'umi';

import {
  HeartOutlined,
  SmileOutlined,
  UserAddOutlined,
  UserOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { PageContainer, ProLayout } from '@ant-design/pro-layout';

import { isArray, _ } from 'lodash';
import type { ProSettings } from '@ant-design/pro-layout';

import QuickNavigation from '@/components/Quick-navigation';
import RightContent from '@/components/GlobalHeader/RightContent';
import BreadcrumbNavigation from '@/components/BreadcrumbNavigation';

import styles from './index.less';

const IconMap = {
  SmileOutlined: <SmileOutlined />,
  HeartOutlined: <HeartOutlined />,
  UserAddOutlined: <UserAddOutlined />,
  UserOutlined: <UserOutlined />,
  TeamOutlined: <TeamOutlined />,
};

const getMenuChild = (arr: any, res: number[]) => {
  const children: any = [];

  arr.forEach((i: any) => {
    if (!i.name) return;
    if (i.id) {
      if (res.includes(i.id)) {
        children.push({
          ...i,
          authorized: i.path,
          path: i.path,
          name: i.name && <FormattedMessage id={i.name} />,
          icon: i.icon,
          children: i.routes ? getMenuChild(i.routes, res) : [],
        });
      }
    } else {
      children.push({
        ...i,
        authorized: i.path,
        path: i.path,
        name: i.name,
        icon: i.icon,
        children: i.routes ? getMenuChild(i.routes, res) : [],
      });
    }
  });

  return children;
};

const HOME_PANE = {
  label: <FormattedMessage id="menu.homepage" />,
  key: '/welcome',
  closable: false,
};

const BasicLayout: React.FC = (props) => {
  const [panes, setPanes] = useState<[any]>([HOME_PANE]);
  const [settings, setSetting] = useState<Partial<ProSettings> | undefined>({
    fixSiderbar: true,
    fixedHeader: true,
    // layout: 'mix',
    // splitMenus: true,
  });
  const [activeKey, setActiveKey] = useState('/welcome');

  const [menu, setMenu] = useState();
  const history = useHistory();

  /**
   * 点击menu时 生成新的tab页面或跳转到已存在的tab页面
   */
  const onNavigate = useCallback((routeInfo) => {
    setActiveKey(routeInfo.key); //保存要高亮的tab key

    // 保存tab的key
    setPanes((p: any) => {
      if (!p.find((item: any) => item.key === routeInfo.key)) {
        const pane = {
          label: routeInfo.name,
          key: routeInfo.path,
        };
        return p.concat(pane);
      }
      return p;
    });
  }, []);

  useEffect(() => {
    request('/api/id').then((resData: any) => {
      const menu: any = [];
      const allowRoutesId = resData.data || [];

      props.route.routes!.forEach((i: any) => {
        if (!i.name) return;
        if (!allowRoutesId.includes(i.id)) return;

        const menuChildren = i.routes
          ? getMenuChild(i.routes, allowRoutesId)
          : null;
        menu.push({
          authorized: i.path,
          path: i.path,
          name: i.name && <FormattedMessage id={i.name} />,
          icon: i.icon && IconMap[i.icon],
          hideInMenu: isArray(menuChildren) ? menuChildren.length === 0 : false,
          children: menuChildren,
        });
      });

      setMenu(menu);
    });
  }, []);

  return (
    // <div
    //   id="test-pro-layout"
    //   style={{
    //     height: '100vh',
    //   }}
    // >
    <ProLayout
      {...settings}
      className={styles.prolayout}
      headerHeight={48}
      navTheme="dark"
      menu={{
        locale: true,
        collapsedShowGroupTitle: true,
      }}
      rightContentRender={() => {
        return <RightContent />;
      }}
      headerContentRender={() => {
        return <BreadcrumbNavigation props={props} />;
      }}
      menuDataRender={() => menu}
      menuItemRender={(item: any, dom) => {
        return (
          <a
            onClick={() => {
              history.push(item.path);
              onNavigate(item);
            }}
          >
            {dom}
          </a>
        );
      }}
    >
      <PageContainer className={styles.title}>
        <QuickNavigation
          panes={panes}
          setPanes={setPanes}
          activeKey={activeKey}
          setActiveKey={setActiveKey}
        />
        <div style={{ marginLeft: '18px', marginRight: '18px' }}>
          {props.children}
        </div>
      </PageContainer>
    </ProLayout>
    // </div>
  );
};

export default BasicLayout;
